<script setup>
import { computed, ref, watch, nextTick } from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { ArrowRightOutlined } from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import LoginModal from "../../components/LoginModal/index.vue";
import PromptUse from "../../components/PromptUse/index.vue";
import PromptReplace from "../../components/PromptReplace/index.vue";
import GroupMoreSvg from "../../common/image/group_more.png";
const route = useRoute();
const router = useRouter();
const aiTxt = ref("");
const config = ref(null);
const aiConfig = ref(null);
const applicationGroupList = ref([]);
const industryGroupList = ref([]);
const message = ref("");
const loginVisible = ref(false);
const promptsModalVisible = ref(false);
const promptReplaceVisible = ref(false);
const iframeContainerVisible = ref(false);
const iframeLoaded = ref(false);
const currentPrompt = ref({});
const collectApps = ref([]);
const collectAppIds = computed(() => {
  return collectApps.value.map((app) => app.id);
});

const getCategoryList = async () => {
  const { applicationList, industryList } = await store.dispatch(
    "GetSceneApps"
  );

  applicationGroupList.value = [
    {
      cat_name: "热门推荐",
      hot: 1,
    },
  ].concat(applicationList);

  industryGroupList.value = industryList;
};

const getApplicationList = async () => {
  const requests = applicationGroupList.value.map((item) => {
    if (item.hot) {
      return request
        .get("/work_ai", "/pc/application/popular/list", { pageSize: 10 })
        .then(({ list }) => {
          console.log(list);
          item.app_list = list;
        });
    }

    return request
      .get("/work_ai", "/application/category/app_list", {
        is_industry: 0,
        cat_id: item.id,
      })
      .then(({ app_list }) => {
        item.app_list = app_list;
      });
  });

  await Promise.all(requests);
};

const getUserCollectApps = async () => {
  const { data } = await request.get("/work_ai", "/user/collect/list", {
    type: "application",
  });
  collectApps.value = data.map((item) => item.collectable);
};

const initData = async () => {
  if (utils.isLogin()) {
    if (route.query.appId) {
      router.push(
        `/sceneModel/scene/${route.query.cateId}?appId=${route.query.appId}`
      );
      return;
    }

    const configInfo = await store.dispatch("GetConfigInfo");
    const system_name = configInfo?.basic?.system_name;

    if (system_name && system_name.slice(-2) && system_name.slice(-2) == "AI")
      aiTxt.value = system_name.slice(-2);

    config.value = configInfo;

    const aiConfigInfo = await store.dispatch("getAiConfig");
    aiConfig.value = aiConfigInfo;

    await getCategoryList();
    await getApplicationList();

    const isLogin = await utils.checkLogin();

    if (isLogin) {
      await getUserCollectApps();
    }
  }

};

// initData();

const industryGroups = computed(() => {
  let groups =
    industryGroupList.value.length > 0
      ? industryGroupList.value
      : applicationGroupList.value.slice(1);

  if (groups.length > 8) {
    groups = groups.slice(0, 8).concat([
      {
        id: 0,
        cat_name: "更多",
        cat_icon: GroupMoreSvg,
      },
    ]);
  }

  return groups;
});

const onIndustryGroupClick = (industryGroup) => {
  if (industryGroupList.value.length === 0) {
    router.push({
      name: "ApplicationHome",
      ...(industryGroup.id ? { query: { cateId: industryGroup.id } } : {}),
    });
    return;
  }

  router.push({
    name: "IndustryModel",
    ...(industryGroup.id ? { query: { cateId: industryGroup.id } } : {}),
  });
};

const onAppClick = (item, group) => {
  const hot = group.hot || 0;

  if (hot) {
    group = applicationGroupList.value.find((group) =>
      group.app_list.some((app) => app.id === item.id && !group.hot)
    );
  }

  router.push(`/sceneModel/scene/${group.id}?appId=${item.id}`);
};

const onCollectClick = (app) => {
  utils.checkLogin().then((isLogin) => {
    if (!isLogin) {
      loginVisible.value = true;
      return;
    }

    const status = collectAppIds.value.includes(app.id) ? 0 : 1;

    request
      .post("/work_ai", "/user/collect", {
        collect_type: "application",
        collect_id: app.id,
        status,
      })
      .then(() => {
        if (status) {
          collectApps.value.push(app);
        } else {
          collectApps.value = collectApps.value.filter(
            (item) => item.id !== app.id
          );
        }
      });
  });
};

// 使用提示词
const usePrompt = (item) => {
  utils.checkLogin().then(async (isLogin) => {
    if (!isLogin) {
      loginVisible.value = true;
      return;
    }

    currentPrompt.value = item;

    if (item.content_matches && item.content_matches.length > 0) {
      promptReplaceVisible.value = true;
    } else {
      const chat_id = await addChatByMessage(item.content);
      router.push(`/chatModel/chat?chat_id=${chat_id}&message=${item.content}`);
    }
  });
};

const replaceCallback = async (list) => {
  if (list && list.length > 0) {
    list.forEach((item) => {
      currentPrompt.value.content = currentPrompt.value.content.replace(
        item[0],
        item[1]
      );
    });

    const chat_id = await addChatByMessage(currentPrompt.value.content);
    router.push(
      `/chatModel/chat?chat_id=${chat_id}&message=${currentPrompt.value.content}`
    );
  }
};

const addChatByMessage = async (message) => {
  const params = {
    title: message.value,
    team_id: utils.getCurrentTeam() || 0,
  };

  const { chat_id } = await request.post("/work_ai", "/chat/add", params);

  return chat_id;
};

const promptReplaceClose = () => {
  promptReplaceVisible.value = false;
  currentPrompt.value = {};
};

const onSendMessageClick = () => {
  utils.checkLogin().then(async (isLogin) => {
    if (!isLogin) {
      loginVisible.value = true;
      return;
    }

    if (message.value) {
      const chat_id = await addChatByMessage(message.value);

      router.push(
        `/chatModel/chat?chat_id=${chat_id}&message=${message.value}`
      );

      return;
    }

    router.push("/chatModel/chat");
  });
};

const loginCallback = () => {
  loginVisible.value = false;
  router.go(0);
};

const openUrl = (url) => {
  window.open(url, "_blank");
};

const noticeList = ref([]);

const getNoticeList = () => {
  request.get("/work_ai", "/user/notice/list").then((res) => {
    noticeList.value = res.result;
  });
};

getNoticeList();

const styles = computed(() => {
  return {
    ...(aiConfig.value?.page_banner
      ? {
        backgroundImage: `url(${aiConfig.value.page_banner})`,
      }
      : {}),
  };
});

watch(iframeContainerVisible, (visible) => {
  if (visible && !iframeLoaded.value) {
    nextTick(() => {
      iframeLoaded.value = true;
    });
  }
});
</script>

<template>
  <div class="page-warp">
    <div class="tag" v-if="noticeList.length">
      <img :src="$utils.staticPath + 'images/workAi/user_pc/horn.png'" class="horn" />
      <div class="container">
        <a-carousel :autoplay="true" :dots="false" :key="1" vertical>
          <div class="marquee" v-for="item in noticeList" :key="item.id">
            {{ item.title }}
          </div>
        </a-carousel>
      </div>
    </div>
    <div class="workbenches-box" :style="styles">
      <div class="flex justify-center page-title">
        <template v-if="aiConfig">
          <span>{{ aiConfig.page_title }}</span>
        </template>
      </div>
      <div class="flex justify-center page-subtitle mt-10" v-if="aiConfig">
        {{ aiConfig.page_subtitle || "用AI提高10倍工作和企业营销效率" }}
      </div>
      <div class="flex justify-center mt-30">
        <div class="search-box flex justify-center align-center">
          <div class="search-prefix-icon">AI</div>
          <div class="search-input flex justify-center align-center">
            <div class="search-input__prefix" @click="promptsModalVisible = true">
              提问示范
            </div>
            <a-input v-model:value="message" placeholder="输入要求，如：写一份后端开发的周报" />
          </div>
          <div class="search-btn ml-5" @click="onSendMessageClick">
            开始创作
          </div>
        </div>
      </div>
      <div class="flex justify-center mt-30">
        <div class="flex category-box">
          <div class="flex category-box__item flex-col align-center" @click="onIndustryGroupClick(industryGroup)"
            v-for="industryGroup in industryGroups" :key="industryGroup.id">
            <div class="category-box__image">
              <img :src="industryGroup.cat_icon" />
            </div>
            <div class="category-box__title">{{ industryGroup.cat_name }}</div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <div class="app-section" v-for="(group, index) in applicationGroupList" :key="index">
        <div class="app-section__title" style="margin-top: 15px;">
          {{ group.cat_name }}
        </div>
        <div class="app-section__list">
          <div class="app-card" v-for="(app, index) in group.app_list" :key="index" @click="onAppClick(app, group)">
            <div class="flex align-center">
              <div class="app-card__image">
                <img :src="app.icon" />
              </div>
              <div class="app-card__title">
                {{ app.name }}
              </div>
            </div>
            <div class="app-card__info">
              {{ app.info }}
            </div>
            <div class="app-card__icon" @click.stop="onCollectClick(app)">
              <CuIcon class="app-card__icon--shoucang" :type="collectAppIds.includes(app.id)
                  ? 'icon-shoucang2'
                  : 'icon-shoucang'
                " />
            </div>
            <ArrowRightOutlined class="app-card__arrow" />
          </div>
        </div>
      </div>
    </div>
    <div class="additional-info" v-if="(config && config.basic) || (aiConfig && aiConfig.about_url)">
      <template v-if="config && config.basic">
        <span style="margin-right: 10px" @click="openUrl('https://beian.miit.gov.cn/')"
          v-if="config.basic.system_domain_icp">{{ config.basic.system_domain_icp }}</span>
        <span style="margin-left: 10px; margin-right: 10px" @click="openUrl('http://www.beian.gov.cn/ ')"
          v-if="config.basic.system_domain_police">{{ config.basic.system_domain_police }}</span>
      </template>
      <template v-if="aiConfig && aiConfig.about_url">
        <span style="margin-left: 10px" @click="openUrl(aiConfig.about_url)">关于我们</span>
      </template>
    </div>

    <template v-if="aiConfig && aiConfig.bubble_image && aiConfig.bubble_url">
      <div style="
          box-sizing: border-box;
          position: fixed;
          right: 4vmin;
          bottom: 4vmin;
          z-index: 99999;
          width: 68px;
          height: 68px;
          overflow: hidden;
          border-radius: 100%;
          color: #fff;
          cursor: pointer;
        " @click="iframeContainerVisible = true">
        <img :src="aiConfig.bubble_image" style="width: 100%; height: 100%" />
      </div>
      <div v-show="iframeContainerVisible" v-if="iframeContainerVisible || iframeLoaded" id="iframe_container" style="
          position: fixed;
          right: 4vmin;
          bottom: calc(4vmin + 68px + 2vmin);
          z-index: 999999;
          width: 520px;
          height: 80vmin;
          border: 1px solid #dcdfe6;
          border-radius: 15px;
        ">
        <div class="close-icon" style="
            position: absolute;
            right: -10px;
            top: -10px;
            height: 30px;
            width: 30px;
            text-align: right;
            color: #7b9efb;
            cursor: pointer;
            background-color: rgba(232, 234, 247, 0.6);
            border-radius: 50%;
            display: none;
            padding: 6px;
          " @click="iframeContainerVisible = false">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" data-v-ea893728="">
            <path fill="currentColor"
              d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z">
            </path>
          </svg>
        </div>
        <iframe id="iframe_cby" :src="aiConfig.bubble_url" style="
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 15px;
            overflow: hidden;
          "></iframe>
      </div>
    </template>
    <LoginModal :visible="loginVisible" @onClose="loginVisible = false" @loginCallback="loginCallback" />

    <PromptUse :visible="promptsModalVisible" @onClose="promptsModalVisible = false" @onSearchSelect="usePrompt" />

    <PromptReplace :prompt="currentPrompt" :visible="promptReplaceVisible" @onClose="promptReplaceClose"
      @replaceCallback="replaceCallback" />
  </div>
</template>

<style lang="less" scoped>
.page-warp {
  padding: 40px 60px;
  width: 100%;
  height: 100%;
  overflow: hidden auto;
  background-image: url(../home/home_bg.png);

  .tag {
    width: 100%;
    display: flex;
    justify-content: left;
    align-items: center;
    padding: 3px 0px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    border: none;
    margin-bottom: 15px;
    margin-top: -20px;

    .horn {
      width: 30px;
      height: 30px;
      object-fit: cover;
      margin-right: 5px;
    }

    .close-circle {
      background: #867d7b;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      color: #f4f5ff;
      font-size: 26px;
    }

    .favorite-tips-box {
      padding: 3px 5px;
      background: #e9ebec;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #6965ea;
      margin: 0 5px;
    }

    .container {
      width: 100%;
      height: 25px;

      .marquee {
        width: 100%;
        height: 25px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        .image {
          margin-right: 8px;
          display: inline-block;
          width: 20px;
          height: 20px;
          line-height: 20px;
          object-fit: cover;
          margin-bottom: 3px;
        }
      }
    }

    :deep(.slick-list) {
      height: 30px;
    }

    :deep(.slick-slide) {
      height: 30px;
    }
  }
}

.workbenches-box {
  background-color: #ac85f3;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  padding: 40px 0px 30px;
  color: #ffffff;
  border-radius: 10px;
}

.page-title {
  font-size: 36px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 16px;
}

.search-box {
  border-radius: 20px;
  background: linear-gradient(to right, #e4dbfd, #deedfe);
  padding: 4px;

  .search-prefix-icon {
    display: none;
    padding: 0px 8px 0px 10px;
    font-weight: bold;
    color: rgb(255, 101, 98);
    font-size: 20px;
    background: linear-gradient(47deg,
        #6554ff 0%,
        #f26dbe 57.0068359375%,
        #febd7f 91.357421875%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .search-input {
    background: #ffffff;
    border-radius: 20px;
    padding: 3px;
    padding-right: 10px;

    &__prefix {
      color: #a27dfd;
      font-size: 12px;
      background: #efe9ff;
      border-top-left-radius: 20px;
      border-bottom-left-radius: 20px;
      height: 26px;
      line-height: 26px;
      padding: 0px 10px 0px 12px;
      cursor: pointer;
    }

    input {
      border: none;
      outline: none;
      width: 320px;
      font-size: 13px;
      margin-left: 5px;
      padding: 0px 10px;

      &:focus {
        border: none;
        box-shadow: none;
      }
    }
  }

  .search-btn {
    background: #ff8986;
    border: 2px solid #fff;
    padding: 3px 7px;
    border-radius: 16px;
    font-size: 13px;
    height: 100%;
    cursor: pointer;
  }
}

.category-box {
  &__item {
    margin-right: 30px;
    cursor: pointer;

    &:last-child {
      margin-right: 0px;
    }
  }

  &__image {
    width: 32px;
    height: 32px;

    img {
      height: 100%;
      width: 100%;
      border-radius: 50%;
      object-fit: cover;
    }
  }

  &__title {
    font-size: 12px;
    margin-top: 5px;
  }
}

.app-section {
  margin-top: 40px;

  // &:first-child .app-section__list {
  //     grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
  // }

  &__title {
    font-size: 16px;
    font-weight: 700;
  }

  &__list {
    margin-top: 15px;
    display: grid;
    gap: 20px;
    grid-template-columns: repeat(5, minmax(0, 1fr));

    .app-card {
      border-radius: 10px;
      background: #fff;
      border: 1px solid #e9e9e9;
      width: 100%;
      padding: 20px 16px 30px;
      cursor: pointer;
      position: relative;

      &__image {
        width: 46px;
        height: 46px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      &__title {
        margin-left: 10px;
        font-size: 16px;
        font-weight: 600;
      }

      &__info {
        margin-top: 20px;
        color: #767676;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      &__icon {
        position: absolute;
        right: 15px;
        top: 10px;
        display: none;

        &--shoucang {
          font-size: 16px;
        }
      }

      &__arrow {
        color: @primary-color;
        position: absolute;
        right: 15px;
        bottom: 10px;
        font-size: 16px;
        visibility: hidden;
      }

      &:hover {
        -webkit-transform: translateY(-3px);
        -ms-transform: translateY(-3px);
        transform: translateY(-3px);
        border: 1px solid @primary-color;

        .app-card__arrow {
          visibility: visible;
        }

        .app-card__icon {
          display: block;
        }
      }
    }
  }
}

.additional-info {
  margin-top: 30px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    color: #bbb;
    cursor: pointer;

    &:hover {
      color: @primary-color;
    }
  }
}

@media (min-width: 1024px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }
  }
}

@media (min-width: 1280px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(4, minmax(0, 1fr));
    }
  }
}

@media (min-width: 1536px) {
  .app-section {
    &__list {
      grid-template-columns: repeat(5, minmax(0, 1fr));
    }
  }
}

#iframe_container:hover {
  .close-icon {
    display: block !important;
  }
}
</style>
